package com.app.twth.base;

import android.util.Log;

import androidx.annotation.NonNull;

import com.app.twth.bean.BaseResponseEntity;
import com.app.twth.net.BaseObserver;
import com.app.twth.net.HandlerException;
import com.app.twth.net.HttpListener;
import com.app.twth.utils.FileUtil;
import com.app.twth.utils.LogUtil;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ****************************************************************
 * 文件名称: BaseModel
 * 文件描述: 防止MVP内存泄漏
 * 注意事项:
 * 版权声明:
 * ****************************************************************
 */
public class BaseModel {
    protected CompositeDisposable compositeDisposable = new CompositeDisposable();//管理订阅事件，用于主动取消网络请求

    //网络请求
    protected void sendRequest(Observable observable, HttpListener listener) {
        observable.subscribeOn(Schedulers.io())
                //.observeOn(AndroidSchedulers.mainThread()) 在工作线程处理
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    public void onData(Object tJsonBase) {
                        listener.onSuccess(tJsonBase);
                    }

                    @Override
                    public void onError(String errorMsg, String code) {
                        Log.e("BaseModel", "11111onError" + errorMsg);
//                        e.printStackTrace();
                        listener.onError(errorMsg, code);
                    }

                    @Override
                    public void onComplete() {
                        Log.e("BaseModel", "onComplete");
                    }
                });
    }

    protected <T> void sendRequest(Call observable, HttpListener listener) {
//        observable.enqueue(new Callback<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                LogUtil.i("response.isSuccessful()"+response.isSuccessful());
//                LogUtil.i("response.body()"+response.body());
//                if (response.isSuccessful()) {
//                    ResponseBody body = response.body();
//                    LogUtil.i("onResponse=");
//                    // 使用ResponseBody进行操作，例如读取数据
//                    try {
//                        String json = body.string();
//                        LogUtil.i("onResponse=" + json);
//                        // 使用Gson解析json
//                        Gson gson = new Gson();
//                        BaseResponseEntity model = gson.fromJson(json, BaseResponseEntity.class);
//                        // 使用model中的数据
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        LogUtil.i("IOException=" );
//                    }
//                }else {
//                    ResponseBody responseBody = response.errorBody();
//                    try (ResponseBody body = responseBody) {
//                        // 将字节流转换为字符串
//                        String response2 = new String(body.bytes(), "UTF-8");
//
//                        // 解析JSON
//                        try {
//                            JSONObject jsonObject = new JSONObject(response2);
//                            // 从这里开始，你可以根据你的需求获取JSON对象中的数据
//                            String string = jsonObject.getString("code");
//                            LogUtil.i("code="+string);
//                        } catch (JSONException e) {
//                            // 处理JSON解析异常
//                        }
//                    } catch (IOException e) {
//                        // 处理IO异常
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t) {
//                LogUtil.i("onFailure=");
//                // 处理错误
//
//            }
//        });
        observable.enqueue(new Callback<BaseResponseEntity<T>>() {
            @Override
            public void onResponse(Call<BaseResponseEntity<T>> call, Response<BaseResponseEntity<T>> response) {
                BaseResponseEntity<T> body = response.body();
                LogUtil.i("onResponse=" + body);
                LogUtil.i("response.errorBody()=" + response.errorBody());


                if (body == null) {
                    ResponseBody responseBody = response.errorBody();
                    try (ResponseBody errorBody = responseBody) {
                        // 将字节流转换为字符串
                        String response2 = new String(errorBody.bytes(), "UTF-8");

                        // 解析JSON
                        try {
                            Gson gson = new Gson();
                            BaseResponseEntity baseResponseEntity = gson.fromJson(response2, BaseResponseEntity.class);
//                            JSONObject jsonObject = new JSONObject(response2);
                            // 从这里开始，你可以根据你的需求获取JSON对象中的数据
//                            String string = jsonObject.getString("code");
                            LogUtil.i("code=" + baseResponseEntity.getCode());
                            if (baseResponseEntity.getMessage() != null) {
                                if (baseResponseEntity.getMessage().contains("login")) {
                                    EventBus.getDefault().post("logout");
                                    return;
                                }
                                if (baseResponseEntity.getMessage().contains("invalid token")) {
                                    EventBus.getDefault().post("logout");
                                    return;
                                }
                            }
                            listener.onError(baseResponseEntity.getMessage(), baseResponseEntity.getCode());
                            return;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        // 处理IO异常
                    }
                    listener.onError("未知错误", "5000");
                    return;
                } else {
                    if (response.code() == 401) {
                        EventBus.getDefault().post("logout");
                        return;
                    } else {
                        BaseResponseEntity baseResponse = (BaseResponseEntity) response.body();
                        if (baseResponse.getMessage() != null) {
                            if (baseResponse.getMessage().contains("login")) {
                                EventBus.getDefault().post("logout");
                                return;
                            }
                            if (baseResponse.getMessage().contains("invalid token")) {
                                EventBus.getDefault().post("logout");
                                return;
                            }
                        }
                    }
                    listener.onSuccess(body.data);
                }


//                if (baseResponseEntity.getCode().equalsIgnoreCase("200")) {//登录过期
//                    listener.onSuccess(baseResponseEntity.data);
//                } else {
//                    listener.onError(baseResponseEntity.getMessage(), baseResponseEntity.getCode() + "");
//                }
            }

            @Override
            public void onFailure(Call<BaseResponseEntity<T>> call, Throwable t) {
                Request request = call.request();
                RequestBody body = request.body();

                LogUtil.i("onResponse,body=" + body);
                LogUtil.i("onResponse,onFailure=" + t.getMessage());
                HandlerException.ResponseThrowable throwable = HandlerException.handleException(t);
                listener.onError(throwable.getMessage(), throwable.getCode());
            }
        });
    }

    //下载请求
    protected void sendDownloadRequest(Observable observable, HttpListener listener, File file) {
        observable.subscribeOn(Schedulers.io())
                .map((Function<ResponseBody, File>) responseBody -> {
                    FileUtil.writeFile(responseBody, file);
                    return file;
                })
                //.observeOn(AndroidSchedulers.mainThread()) 在工作线程处理
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (compositeDisposable != null)
                            compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull Object o) {
                        listener.onSuccess(o);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        HandlerException.ResponseThrowable throwable = HandlerException.handleException(e);
                        listener.onError(throwable.getMessage(), throwable.getCode());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //主动解除所有订阅者
    protected void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
    }
}
